﻿#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Reflection;

namespace BF
{
    public static class TypeUtils
    {
        private readonly static Assembly Assembly_CSharp = Assembly.Load("Assembly-CSharp");

        private static string[] ignoreAssemblies = { "UnityEditor" };

        public static Type FindTypeByName(string name)
        {
            switch (name)
            {
                case "string": return typeof(string);
                case "sbyte": return typeof(sbyte);
                case "short": return typeof(short);
                case "int": return typeof(int);
                case "long": return typeof(long);
                case "byte": return typeof(byte);
                case "ushort": return typeof(ushort);
                case "uint": return typeof(uint);
                case "ulong": return typeof(ulong);
                case "float": return typeof(float);
                case "double": return typeof(double);
                case "bool": return typeof(bool);
                case "char": return typeof(char);
                case "decimal": return typeof(decimal);
                case "DateTime": return typeof(DateTime);
                default: break;
            }

            try
            {
                {
                    Type type = Type.GetType(name);
                    if (type != null)
                    {
                        return type;
                    }
                    type = Assembly_CSharp.GetType(name);
                    if (type != null)
                    {
                        return type;
                    }
                }

                Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
                foreach (Assembly assembly in assemblies)
                {
                    if (!Array.Exists(ignoreAssemblies, assembly.FullName.StartsWith))
                    {
                        continue;
                    }

                    Type type = assembly.GetType(name);
                    if (type != null)
                    {
                        return type;
                    }
                }
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
            return null;
        }
    }
}
#endif